package com.hejia.bulbul.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hejia.alauda.entity.Feedback;
import com.hejia.alauda.service.FeedbackService;
import com.hejia.alauda.utils.HttpResponse;
import com.hejia.alauda.utils.Pager;
import com.hejia.alauda.utils.PagerHelper;


/**
 * 用户反馈控制器
 * @author hyr
 *
 */
@Controller
@RequestMapping("feedbacks")
public class FeedbackController {
	
	@Resource
	private FeedbackService feedbackService;
	
	@RequestMapping("{id}/reply")
	public String editReply(@PathVariable Long id, ModelMap model){
		
		Feedback feedback = feedbackService.findFeedbackById(id);
		model.put("feedback", feedback);
		
		return "feedback/reply";
	}
	
	@RequestMapping(value="{id}/reply", method=RequestMethod.PUT)
	@ResponseBody
	public HttpResponse reply(Feedback feedback, ModelMap model){
		
		HttpResponse response = new HttpResponse();
		
		try{
			feedback = feedbackService.replyFeedback(feedback);
			
			response.setCode(HttpResponse.CODE_OK);
			response.setStatus(HttpResponse.STATUS_SUCCESS);
			response.setMessage("处理反馈成功");
			response.setData(feedback);
		}catch(Exception e){
			response.setCode(HttpResponse.CODE_INTERNAL_SERVER_ERROR);
			response.setStatus(HttpResponse.STATUS_FAIL);
			response.setMessage("处理反馈失败");
			response.setData(feedback);
		}
		
		return response;
	}
	
	@RequestMapping
	public String list(
			String keyword,
			Feedback.Status status,
			Pager<Feedback> pager,
			ModelMap model){
		
		pager = feedbackService.findFeedbacksByKeywordAndStatus(keyword, status, pager);
		
		PagerHelper<Feedback> helper = new PagerHelper<>();
        helper.setPager(pager);
        Map<String, String> map = new HashMap<>();
        if (keyword != null) {
            map.put("keyword", keyword);
        }
        if (status != null) {
            map.put("status", status.toString());
        }
        helper.setParams(map);
        helper.setBaseUrl("/feedbacks");
        
        model.put("pagerHelper", helper);
		model.put("keyword", keyword);
		model.put("status", status);
		model.put("feedbacks", pager);
		
		return "feedback/list";
	}
}
